﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KC.ExtensionMethods;
using DAL = KC.DataAccess;

namespace KC.Business.Net.Tracking
{
	public static class SearchEngines
	{

		/// <summary>Finds my current top rank on Google for a given term</summary>
		/// <param name="query">Query to Google</param>
		/// <returns>int representing the hit number on the Google search results</returns>
		public static int FindGooglePosition(string query)
		{
			string GoogleUrl = @"http://www.google.com/search?hl=en&source=hp&aq=f&oq=&aqi=g10&start={0}&q={1}";
			string html = "";
			for (int CurPage = 0; CurPage < 10; CurPage++)
			{
				html = DAL.Net.Net.DownloadPage(string.Format(GoogleUrl, new string[] { CurPage.ToString(), HttpUtility.UrlEncode(query) }));

				List<string> links = KC.Business.Net.Web.GetLinksFromHtml(html);
				List<string> links2 = new List<string>();
				foreach (string link in links)
					if (link.ToLower().Contains("class=l"))
						links2.Add(link);

				for (int i = 0; i < links2.Count; i++)
					if (new Uri(links2[i]).isMyDomain())
						return (CurPage * KC.Constants.Net.SearchEngineHitsPerPage) + i + 1;
			}
			return -1;
		}

	}
}
